﻿package am.fp.toolbars
{ 
  import fl.controls.Slider;
  import fl.controls.TextInput;
  import fl.events.SliderEvent;
  import fl.events.ComponentEvent;

  import flash.events.FocusEvent; 
  import flash.events.TextEvent;

  import com.yahoo.astra.fl.containers.HBoxPane;
  
  import am.fp.Toolbar;
  import am.fp.FPDispatcher;
  import am.fp.events.ZoomEvent;
  
  /**
   * Toolbar containing the zoom controls.
   */
  public class Zoom extends Toolbar
  { 
    private var m_slider: Slider;
    private var m_tiPercent: TextInput;
    private var m_currentPercent: int;
    
    public function Zoom()
    {
      paddingLeft = 5;
      paddingTop = 2;
      
      var sliderContainer: HBoxPane = addContainer(6, 6);
      m_slider = new Slider();
      m_slider.width = 100;
      m_slider.height = 16;
      m_slider.minimum = ZoomEvent.MIN;
      m_slider.maximum = ZoomEvent.MAX;
      m_slider.liveDragging = true;
      sliderContainer.addChild(m_slider);
      sliderContainer.paddingRight = 3;
      
      m_tiPercent = new TextInput();
      m_tiPercent.width = 38;
      m_tiPercent.text = "";
      m_tiPercent.height = TEXTFIELDS_HEIGHT;
      m_tiPercent.maxChars = 5;
      m_tiPercent.restrict = "0-9";
      m_tiPercent.addEventListener(FocusEvent.FOCUS_IN, onZoomPercentFocusIn, false, 0, true);
      m_tiPercent.addEventListener(FocusEvent.FOCUS_OUT, onZoomPercentFocusOut, false, 0, true);
      m_tiPercent.addEventListener(ComponentEvent.ENTER, onZoomPercentEnterKey, false, 0, true);
      addChild(m_tiPercent);

      FPDispatcher.instance.addEventListener(ZoomEvent.ZOOM_UPDATED, onZoomUpdated, false, 0, true);
      
      m_slider.addEventListener(SliderEvent.CHANGE, onChangeZoom, false, 0, true);
    }

    private function onZoomUpdated(e: ZoomEvent): void
    {
      m_currentPercent = e.value;
      m_slider.value = m_currentPercent;
      m_tiPercent.text = m_currentPercent + "%";
    }
    
    private function onChangeZoom(e: SliderEvent): void
    {
      m_tiPercent.text = e.value + "%";
      FPDispatcher.instance.dispatchEvent(new ZoomEvent(ZoomEvent.CHANGE, e.value));
    }
    
    private function onZoomPercentFocusIn(e: FocusEvent): void
    {
      m_tiPercent.text = String(m_currentPercent);
    }

    private function onZoomPercentFocusOut(e: FocusEvent): void
    {
      m_tiPercent.text = m_currentPercent + "%";
    }
    
    private function onZoomPercentEnterKey(e: ComponentEvent): void
    {
      FPDispatcher.instance.dispatchEvent(new ZoomEvent(ZoomEvent.CHANGE, Math.min(Math.max(int(m_tiPercent.text), m_slider.minimum), m_slider.maximum)));
      setFocus();
    }
    
    override protected function enableButtons(box: HBoxPane, bEnabled: Boolean): void
    {
      super.enableButtons(box, bEnabled);
      if (box == this && !bEnabled)
      {
        m_tiPercent.text = "";
        m_slider.value = m_slider.minimum;
      }
    }
  }
}

